package sale_admin

import (
	"context"
	"encoding/json"
	"sale-admin/config/mysql"
	"sale-admin/internal/app/grpc/protoc/sale_adminc"
	"sale-admin/internal/app/web/service/express"
	"sale-admin/internal/app/web/service/goods"
	"sale-admin/internal/dao"
)

func (s SaleAdminService) ExpressFee(ctx context.Context, req *sale_adminc.ExpressFeeReq) (*sale_adminc.ExpressFeeRsp, error) {
	var msg string
	fee, err := goods.GoodsService{}.GetExpressFee(ctx, req.GoodsId, req.Province)
	if err != nil {
		msg = err.Error()
	}
	rsp := &sale_adminc.ExpressFeeRsp{
		Fee: fee,
		Msg: msg,
	}
	return rsp, nil
}

func (s SaleAdminService) ShipmentInfo(ctx context.Context, req *sale_adminc.ShipmentInfoReq) (*sale_adminc.ShipmentInfoRsp, error) {
	info := dao.OrderShipmentInfo{}.Get(ctx, mysql.NewDB(), req.OutTradeNo)
	return &sale_adminc.ShipmentInfoRsp{
		ExpressNum: info.ExpressNum,
		ExpressCom: express.ExpressCompanyMap[info.ExpressCom],
	}, nil
}
func (s SaleAdminService) ShippingTracking(ctx context.Context, req *sale_adminc.ShippingTrackingReq) (*sale_adminc.ShippingTrackingRsp, error) {
	record := dao.OrderShippingTracking{}.List(ctx, mysql.NewDB(), req.OutTradeNo)
	if record.Data == "" {
		return &sale_adminc.ShippingTrackingRsp{
			Tracking: nil,
		}, nil
	}
	// 解析轨迹数据
	var tracks []dao.KD100TrackData
	json.Unmarshal([]byte(record.Data), &tracks)

	// 将每条轨迹数据转为json，便于grpc传输
	var trackingRecord []string
	for _, trackData := range tracks {
		dataJson, _ := json.Marshal(trackData)
		trackingRecord = append(trackingRecord, string(dataJson))
	}
	return &sale_adminc.ShippingTrackingRsp{
		Tracking: trackingRecord,
	}, nil
}
